package com.beadwallet.alarm.service.msg.impl;

import com.beadwallet.alarm.service.msg.ShortMsgService;
import com.beadwallet.alarm.util.PropertiesUtil;
import com.beadwallet.alarm.util.StringUtil;
import com.beadwallet.alarm.util.SHA256Util;
import com.beadwallet.common.enums.CodeEnum;
import com.beadwallet.common.utils.StringUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import static com.beadwallet.common.controller.BaseController.respJson;

/**
 * 短信发送：
 * type : 短信类型
 * templateId : 模板Id
 * mobiles : 发送通知类短信手机号码
 * mobile : 发送验证码类短信手机号码
 * parameters : 自定义模板参数
 *
 * @author xingx
 * @date 2017/12/8
 */
@Service
public class ShortMsgSendImpl implements ShortMsgService {
    private static Logger logger = LoggerFactory.getLogger(ShortMsgSendImpl.class);

    private static OkHttpClient client = null;

    static {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(100);
        dispatcher.setMaxRequestsPerHost(100);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        client = builder.dispatcher(dispatcher).build();
    }

    @Override
    public String send(String type, String templateId, String mobiles, String parameters) {
        //获取properties对象
        Properties properties = PropertiesUtil.getProperties();
        try {
            properties.load(ShortMsgSendImpl.class.getResourceAsStream("/msg.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(StringUtil.isEmpty(type) || StringUtil.isEmpty(templateId) || StringUtil.isEmpty(mobiles)){
            return respJson(CodeEnum.FAILURE);
        }

        long timestamp = System.currentTimeMillis();
        Map<String, String> params = new HashMap<>(16);
        // 设置请求参数
        params.put("templateId", templateId);
        String send_url = null;
        StringBuffer buffer = new StringBuffer();
        //将手机号码格式拼接为[xxx,xxx]
        buffer.append("[");
        String[] mobilesArr = mobiles.split(",");
        for(int i=0;i<mobilesArr.length;i++){
            buffer.append(mobilesArr[i]);
            if(i<mobilesArr.length-1) {
                buffer.append(",");
            }
        }
        buffer.append("]");
        //判断短信发送的类型
        String notify = "notify";
        String code = "code";
        if(type.equals(notify)) {
            params.put("mobiles", String.valueOf(buffer));
            send_url=properties.getProperty("base_url")+"/notify/send";
        }else if(type.equals(code)){
            params.put("mobile", String.valueOf(buffer).substring(1, 12));
            send_url=properties.getProperty("base_url")+"/code/send";
        }
        params.put("timestamp", String.valueOf(timestamp));
        if(StringUtils.isEmpty(parameters)){
            parameters="[]";
            params.put("params", parameters);
        }else {
            StringBuffer stringBuffer = new StringBuffer();
            String[] parametersArr = parameters.split(",");
            stringBuffer.append("[");
            for (int i = 0; i < parametersArr.length; i++) {
                stringBuffer.append("\"");
                stringBuffer.append(parametersArr[i]);
                stringBuffer.append("\"");
                if (i < parametersArr.length - 1) {
                    stringBuffer.append(",");
                }
            }
            stringBuffer.append("]");
            params.put("params", String.valueOf(stringBuffer));
        }
        Map<String, Object> sortedMap = new TreeMap<>((arg0, arg1) -> {
            // 忽略大小写
            return arg0.compareToIgnoreCase(arg1);
        });
        // 请求参数排序
        sortedMap.putAll(params);
        // 计算数字签名
        StringBuilder sb = new StringBuilder();
        FormBody.Builder formBody = new FormBody.Builder();
        for (String s : sortedMap.keySet()) {
//            System.out.println(s + "  " + sortedMap.get(s));
            formBody.add(s, sortedMap.get(s) + "");
            sb.append(String.format("%s=%s&", s, sortedMap.get(s)));
        }
        //拼接短信密钥
        sb.append(properties.getProperty("secret"));
        String sig = SHA256Util.sha256Hex(sb.toString());
        // 追加数字签名参数
        RequestBody body = formBody.add("signature", sig).build();
        Request request = new Request.Builder().url(send_url).post(body).build();
        try {
            Response response = client.newCall(request).execute();
            logger.warn("响应结果：{}", response);
            logger.warn("response body string : {}"+response.body().string());
            if(response.code()==200){
                return CodeEnum.SUCC.getCode();
            }else{
                return CodeEnum.FAILURE.getCode();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CodeEnum.FAILURE.getCode();
    }
}
